package com.gress.shop.service.impl;

import com.gress.shop.bo.Email;
import com.gress.shop.bo.example.EmailExample;
import com.gress.shop.constants.EmailConstants;
import com.gress.shop.dao.IEmailDao;
import com.gress.shop.service.IEmailService;
import com.gress.shop.util.HappyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created xiongwen with 2018/4/10 19:55
 * Description:
 */
@Service
public class EmailService implements IEmailService {

    @Resource
    private IEmailDao emailDao;

    @Override
    public int insertSelective(Email record) {
        //设置未读
        record.setOpThree(EmailConstants.Type.NOT_CHECKED);
        return emailDao.insertSelective(record);
    }

    @Override
    public List<Email> selectByExample(EmailExample example) {
        return emailDao.selectByExample(example);
    }

    @Override
    public Email selectByPrimaryKey(String id) {
        return emailDao.selectByPrimaryKey(id);
    }

    @Override
    public void identificationCheck(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new HappyException("系统异常,无法标识已读");
        }
        Email email = new Email();
        email.setId(id);
        email.setOpThree(EmailConstants.Type.CHECKED);
        emailDao.updateByPrimaryKeySelective(email);
    }

    @Override
    @Transactional
    public void identificationByTo(String to) {
        List<Email> emailList = queryNotCheckEmail(to);
        emailList.forEach(e->{
            String id = e.getId();
            identificationCheck(id);
        });
    }

    @Override
    public List<Email> queryCheckEmail(String to) {
        EmailExample example = new EmailExample();
        example.createCriteria()
                .andIsValidEqualTo(1)
                .andOpThreeEqualTo(EmailConstants.Type.CHECKED);
        return emailDao.selectByExample(example);
    }

    @Override
    public List<Email> queryNotCheckEmail(String to) {
        EmailExample example = new EmailExample();
        example.createCriteria()
                .andIsValidEqualTo(1)
                .andOpThreeEqualTo(EmailConstants.Type.NOT_CHECKED);
        return emailDao.selectByExample(example);
    }

    @Override
    public List<Email> queryEmailByTo(String to) {
        EmailExample example = new EmailExample();
        example.createCriteria()
                .andIsValidEqualTo(1);
        return emailDao.selectByExample(example);
    }
}
